package application;

import java.io.InputStream;
import java.util.Hashtable;

import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VolumeControl;

public class SoundManager {
	Hashtable cache=new Hashtable();
	Player p;
	VolumeControl control;
	boolean mute; 
	
	public void playVideo (String mp3resourcePath){
		try {
			if (p!=null) {
				p.stop();
				
			}
		    InputStream is = load(mp3resourcePath);
		    p = Manager.createPlayer(is, "video/mp4");
		    p.setLoopCount(1);
		    p.start();
			control = (VolumeControl) p.getControl("VolumeControl");
			control.setLevel(60);
			control.setMute(mute);			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void playMusic(String mp3resourcePath) {
		try {
			if (p!=null) {
				p.stop();
				p.close();
			}
		    InputStream is = load(mp3resourcePath);
		    p = Manager.createPlayer(is, "audio/mpeg");
		    p.setLoopCount(-1);
		    p.start();
			control = (VolumeControl) p.getControl("VolumeControl");
			control.setLevel(70);
			control.setMute(mute);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void mute(boolean b) {
		this.mute = b;
		if (control!=null)
			control.setMute(b);
	}

	private InputStream load(String mp3File) {
		InputStream is;
		if (cache.contains(mp3File))
			is = (InputStream) cache.get(mp3File);
		else { 
			is = getClass().getResourceAsStream(mp3File);
			cache.put(mp3File,is);
		}
		return is;
	}

	public boolean isMute() {
		return mute;
	}
}
